// pages/home/home.js
const {http} = require("../../utils/util")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentCity:"",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  async onShow(){
    var city = wx.getStorageSync('city')
    if(city){
      this.setData({currentCity:city})
    }
    wx.getLocation({
      type:"wgs84",
      altitude: false,
      success:res=>{
        var {latitude,longitude} = res;
        var key = "FS4BZ-4S4WI-72LGM-5ALZR-VDPEV-DSFTF";
        var url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${key}&get_poi=1`;
        http({
          url,
          success:res=>this.handleCity(res)
        })
      }
    })
  },
  
  handleCity(res){
    var currentCity = res.data.result.address_component.city;
    var storageCity = wx.getStorageSync('city');
    if(storageCity == ""){
      storageCity = currentCity
    }
    if(currentCity != storageCity){
      this.sure(currentCity,storageCity)
    }
    this.setData({currentCity})
  },

  changeCity(result,currentCity,storageCity){
    if(result.confirm){
      this.setData({currentCity})
      wx.setStorageSync('city', currentCity)
    }else{
      this.setData({currentCity:storageCity})
    }
  },

  sure(currentCity,storageCity){
    wx.showModal({
      cancelColor: '#000000',
      cancelText: '取消',
      confirmColor: '#3CC51F',
      confirmText: '确定',
      content: '当前城市不是您所在的城市，是否切换为所在城市？',
      showCancel: true,
      title: '切换城市',
      success: (result) => this.changeCity(result,currentCity,storageCity),
    })
  },

  navigate(){
    wx.navigateTo({
      url: '/pages/city/city',
    })
  }
})